﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MVC.Web.UI.Attributes;

namespace MVC.Web.UI.Tabs
{
    public class WebTabBuilder :  IControlBuilder<WebTabBuilder>
    {

        private WebTab _webTab = null;
        private HtmlHelper _helper = null;
       
        public WebTabBuilder(HtmlHelper helper ) 
        {
            this._helper = helper;
            this._webTab = new WebTab(helper);
        }

        public WebTabBuilder() 
        {           
        }

        #region Methods

        public WebTabBuilder Cache(bool cache)
        {
            this._webTab.Cache = cache;
            return this;
        }
        public WebTabBuilder Collapsible(bool collapsible)
        {
            this._webTab.Collapsible = collapsible;
            return this;
        }


        public WebTabBuilder Selected(int index)
        {
        // this._webTab.TabItems
            if (index > this._webTab.TabItems.Count)
                throw new IndexOutOfRangeException("such index does not exist");
            this._webTab.Selected = index;
            return this;
        }

        public WebTabBuilder Spinner(string spinner)
        {
            this._webTab.Spinner = spinner;
            return this;
        }

        public WebTabBuilder Name(string name)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException("name can not be null");
            this._webTab.Name = name;
            this._webTab.Attributes.Add("id", this._webTab.Name);
            return this;
        }

        public WebTabBuilder AddHandler(TabEvents tabEvent, string handler)
        {
            if (string.IsNullOrEmpty(handler))
                throw new ArgumentNullException("handler can not be null or empty");
       
            this._webTab.TabEventHandlers.Add(tabEvent, handler);
            return this;
        }

        public WebTabBuilder Items(Action<TabBuilder> action)
        {
            TabBuilder tabBuilder = new TabBuilder(this._webTab.TabItems, this._webTab.TabIdPrefix);
            //Tab tab = (Tab)tabBuilder.GetItem();
            action.Invoke(tabBuilder);
            return this;
        }


        public WebTabBuilder TabPrefixes(string prefix)
        {
           if (string.IsNullOrEmpty(prefix))
                throw new ArgumentNullException("prefix can not be null or empty");

           this._webTab.TabIdPrefix = prefix;
           return this;
        }

        /// <summary>
        /// The indexes of tabs that will be disabled
        /// </summary>
        /// <param name="indexes"> </param>
        /// <returns>WebTabBuilder</returns>
        public WebTabBuilder Disabled(int[] indexes)
        {
            if (indexes == null)
                throw new ArgumentNullException("Parameter indexes can not be null");
          
            this._webTab.Disabled = indexes;
            return this;
        }

        /// <summary>
        /// Determines how the tabs content will be loaded  async or not
        /// </summary>
        /// <param name="async"> Determines how the tabs content will be loaded  async or not</param>
        /// <returns></returns>
        public WebTabBuilder AjaxOption(bool async)
        {

            this._webTab.AjaxOptions = async;
            return this;
        }


        private string ConfigureTab()
        {
            // Create tag builder
            var scriptBuilder = new TagBuilder("script");
            scriptBuilder.MergeAttribute("type", "text/javascript");

            StringBuilder innerScriptBlock = new StringBuilder();
            innerScriptBlock.Append("\n\t$(function(){");
            innerScriptBlock.Append("\n\t  $('#" + this._webTab.Name + "').tabs({");

        
            innerScriptBlock.Append(
               "\n\t\tajaxOptions: { async : " + ((this._webTab.AjaxOptions != false) ? "true" : "false") +"}"+","+
                "\n\t\tselected: " + this._webTab.Selected +","+
                "\n\t\tcollapsible: " + this._webTab.Collapsible.ToString().ToLower()+ ","+
                "\n\t\tcache: " + this._webTab.Cache.ToString().ToLower() + "," +
                "\n\t\tdisabled: [" + this.DisabledHelper()+ "]"      
                         
              //  "\n\t\tevent:" + this._event.ToString() + "," +
              // "\n\t\tspinner: '" + this._spinner + "' ," +            
           );
            innerScriptBlock.Append("});");

            //Map all registered handlers to the client side events of the control    
            foreach (KeyValuePair<TabEvents, string> item in this._webTab.TabEventHandlers)
            {
                innerScriptBlock
               .Append("\n\t  $('#" + this._webTab.Name + "').bind('" + ((TabEvents)item.Key).GetStringValue() + "'," + item.Value + ")");
            }

            innerScriptBlock.Append("\n\t});\n ");
            scriptBuilder.InnerHtml = innerScriptBlock.ToString();
            return "<!--  //-->" + "\n    " + scriptBuilder.ToString(TagRenderMode.Normal);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private string DisabledHelper() 
        {
            string tabsToBeDesabled = string.Empty;

            if (this._webTab.Disabled != null)
            {
                int[] indexes = this._webTab.Disabled;
                
                //Check whether there is a such Tab in the collection 
                for (int i = 0; i < indexes.Length; i++)
                {
                    if (indexes[i] > _webTab.TabItems.Count)
                    {
                        throw new NotSupportedException(" There is no Tab with such index " + indexes[i]);
                    }
                }

                //Format the returned string 
                for (int i = 0; i < indexes.Length; i++)
                {
                    if (indexes[i] != indexes[indexes.Length - 1])
                    {
                        tabsToBeDesabled += string.Format("{0},", indexes[i].ToString());
                    }
                    else
                    {
                        tabsToBeDesabled += string.Format("{0}", indexes[i].ToString());
                    }
                }       
            }
            return tabsToBeDesabled;
        }

        #endregion


        public  WebTabBuilder GetItem()
        {
            throw new NotImplementedException();
        }

        public void Render()
        {
            this._webTab.Scripts = this.ConfigureTab();
            this._webTab.RenderControl(this._helper.ViewContext);
        } 
    }
}
